using AgentFrameworkDemo.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;

namespace AgentFrameworkDemo.Services;

/// <summary>
/// 系统提示服务
/// 负责处理和管理Agent的系统提示模板
/// </summary>
public interface ISystemPromptService
{
    /// <summary>
    /// 获取Agent的系统提示
    /// </summary>
    /// <param name="agent">Agent实例</param>
    /// <param name="customVariables">自定义变量，用于替换模板中的占位符</param>
    /// <returns>格式化的系统提示</returns>
    string GetSystemPrompt(Agent agent, Dictionary<string, object>? customVariables = null);

    /// <summary>
    /// 从配置文件获取模板
    /// </summary>
    /// <param name="templateName">模板名称</param>
    /// <returns>模板内容</returns>
    string GetTemplate(string templateName);

    /// <summary>
    /// 替换模板变量
    /// </summary>
    /// <param name="template">模板内容</param>
    /// <param name="variables">变量字典</param>
    /// <returns>替换后的内容</returns>
    string ReplaceVariables(string template, Dictionary<string, object> variables);
}

public class SystemPromptService : ISystemPromptService
{
    private readonly IConfiguration _configuration;
    private readonly ILogger<SystemPromptService> _logger;

    // 缓存模板以提高性能
    private readonly Dictionary<string, string> _templateCache = new();

    public SystemPromptService(IConfiguration configuration, ILogger<SystemPromptService> logger)
    {
        _configuration = configuration;
        _logger = logger;
        LoadTemplates();
    }

    /// <summary>
    /// 获取Agent的系统提示
    /// </summary>
    public string GetSystemPrompt(Agent agent, Dictionary<string, object>? customVariables = null)
    {
        try
        {
            // 1. 如果有自定义系统提示，直接使用
            if (!string.IsNullOrEmpty(agent.Definition.CustomSystemPrompt))
            {
                _logger.LogDebug("Using custom system prompt for agent: {AgentId}", agent.Id);
                return ReplaceVariables(agent.Definition.CustomSystemPrompt, BuildVariables(agent, customVariables));
            }

            // 2. 从配置获取模板
            var templateName = agent.Definition.SystemPromptTemplate;
            var template = GetTemplate(templateName);

            // 3. 如果模板不存在，使用默认模板
            if (string.IsNullOrEmpty(template))
            {
                template = GetTemplate("DefaultTemplate") ?? GenerateDefaultPrompt(agent);
                _logger.LogWarning("Template '{TemplateName}' not found, using default template for agent: {AgentId}",
                    templateName, agent.Id);
            }

            // 4. 替换变量
            var variables = BuildVariables(agent, customVariables);
            var result = ReplaceVariables(template, variables);

            _logger.LogDebug("Generated system prompt for agent: {AgentId}, length: {Length}", agent.Id, result.Length);
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error generating system prompt for agent: {AgentId}", agent.Id);
            return GenerateDefaultPrompt(agent);
        }
    }

    /// <summary>
    /// 从配置文件获取模板
    /// </summary>
    public string GetTemplate(string templateName)
    {
        if (_templateCache.TryGetValue(templateName, out var cachedTemplate))
        {
            return cachedTemplate;
        }

        var template = _configuration[$"AgentFramework:SystemPrompts:Templates:{templateName}"];
        if (string.IsNullOrEmpty(template))
        {
            template = _configuration[$"AgentFramework:SystemPrompts:{templateName}"];
        }

        if (!string.IsNullOrEmpty(template))
        {
            _templateCache[templateName] = template;
        }

        return template ?? string.Empty;
    }

    /// <summary>
    /// 替换模板变量
    /// </summary>
    public string ReplaceVariables(string template, Dictionary<string, object> variables)
    {
        if (string.IsNullOrEmpty(template))
            return string.Empty;

        var result = template;

        foreach (var variable in variables)
        {
            var placeholder = $"{{{variable.Key}}}";
            var value = variable.Value?.ToString() ?? string.Empty;
            result = result.Replace(placeholder, value);
        }

        return result;
    }

    /// <summary>
    /// 加载所有模板到缓存
    /// </summary>
    private void LoadTemplates()
    {
        try
        {
            // 加载默认模板
            var defaultTemplate = _configuration["AgentFramework:SystemPrompts:DefaultTemplate"];
            if (!string.IsNullOrEmpty(defaultTemplate))
            {
                _templateCache["DefaultTemplate"] = defaultTemplate;
            }

            // 加载预设模板
            var templatesSection = _configuration.GetSection("AgentFramework:SystemPrompts:Templates");
            if (templatesSection.Exists())
            {
                foreach (var template in templatesSection.GetChildren())
                {
                    _templateCache[template.Key] = template.Value ?? string.Empty;
                }
            }

            _logger.LogInformation("Loaded {Count} system prompt templates", _templateCache.Count);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error loading system prompt templates");
        }
    }

    /// <summary>
    /// 构建变量字典
    /// </summary>
    private Dictionary<string, object> BuildVariables(Agent agent, Dictionary<string, object>? customVariables)
    {
        var variables = new Dictionary<string, object>
        {
            ["AgentName"] = agent.Definition.Name,
            ["Description"] = agent.Definition.Description,
            ["ToolCapabilities"] = GetToolCapabilitiesText(agent),
            ["MemoryCapabilities"] = GetMemoryCapabilitiesText(agent)
        };

        // 添加配置中的工具信息
        var availableTools = _configuration["AgentFramework:SystemPrompts:Capabilities:AvailableTools"] ?? "数学计算、日期时间查询、文本处理、天气查询";
        variables["AvailableTools"] = availableTools;

        // 添加自定义变量（会覆盖默认变量）
        if (customVariables != null)
        {
            foreach (var variable in customVariables)
            {
                variables[variable.Key] = variable.Value;
            }
        }

        return variables;
    }

    /// <summary>
    /// 获取工具能力描述文本
    /// </summary>
    private string GetToolCapabilitiesText(Agent agent)
    {
        var templateKey = agent.Definition.Capabilities.EnableTools ? "Enabled" : "Disabled";
        var template = _configuration[$"AgentFramework:SystemPrompts:Capabilities:Tools:{templateKey}"] ?? string.Empty;
        var availableTools = _configuration["AgentFramework:SystemPrompts:Capabilities:AvailableTools"] ?? "数学计算、日期时间查询、文本处理、天气查询";

        return ReplaceVariables(template, new Dictionary<string, object>
        {
            ["AvailableTools"] = availableTools
        });
    }

    /// <summary>
    /// 获取记忆能力描述文本
    /// </summary>
    private string GetMemoryCapabilitiesText(Agent agent)
    {
        var templateKey = agent.Definition.Capabilities.EnableMemory ? "Enabled" : "Disabled";
        return _configuration[$"AgentFramework:SystemPrompts:Capabilities:Memory:{templateKey}"] ?? string.Empty;
    }

    /// <summary>
    /// 生成默认系统提示（备用方案）
    /// </summary>
    private string GenerateDefaultPrompt(Agent agent)
    {
        var prompt = $"你是{agent.Definition.Name}。{agent.Definition.Description}\n\n";

        if (agent.Definition.Capabilities.EnableTools)
        {
            prompt += "你可以使用以下工具：数学计算、日期时间查询、文本处理、天气查询。\n";
        }

        if (agent.Definition.Capabilities.EnableMemory)
        {
            prompt += "你有记忆功能，可以记住之前的对话内容。\n";
        }

        prompt += "请根据用户的需求提供帮助，如果需要使用工具，请明确说明。";

        return prompt;
    }
}